﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DataSessionProvider.cs" company="SaltFx">
//   Copyright (c) SaltFx - All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace SaltFx.Data.RavenDB
{
	using Raven.Client;

	/// <summary>
	/// The RavenDB data session provider.
	/// </summary>
	public class DataSessionProvider : IDataSessionProvider<IDocumentSession>
	{
		#region Constants and Fields

		/// <summary>
		/// The session factory builder.
		/// </summary>
		private readonly IDocumentStoreBuilder documentStoreBuilder;

		/// <summary>
		/// The document store.
		/// </summary>
		private IDocumentStore documentStore;

		#endregion

		/// <summary>
		/// Initializes a new instance of the <see cref="DataSessionProvider"/> class.
		/// </summary>
		/// <param name="documentStoreBuilder">The session factory.</param>
		public DataSessionProvider(IDocumentStoreBuilder documentStoreBuilder)
		{
			this.documentStoreBuilder = documentStoreBuilder;
		}

		#region Public Methods and Operators

		/// <summary>
		/// Creates an NHibernate data session instance.
		/// </summary>
		/// <returns>
		/// A new data session.
		/// </returns>
		public IDocumentSession Create()
		{
			Guard.Will.ThrowException(Strings.NoSessionFactory).When(this.documentStoreBuilder == null);

			if (this.documentStore == null)
			{
				this.documentStore = this.documentStoreBuilder.Build();

				this.documentStore.Initialize();
			}

			var session = this.documentStore.OpenSession();

			return session;
		}

		#endregion
	}
}